#include "http.hpp"
#include <functional>

#define WWWROOT "./wwwroot/"

// 将请求转字符串
// 这个简单的服务器的功能是：
// 将对方发来的请求转换成字符串，再用这个字符串填充响应信息发送给对方
// 当然还能保存客户端发送过来的文件，保存在wwwroot中
std::string RequestStr(const HttpRequest &req) 
{
    std::stringstream ss;
    ss << req._method << " " << req._path << " " << req._version << "\r\n";
    for (auto &it : req._params) {
        ss << it.first << ": " << it.second << "\r\n";
    }
    for (auto &it : req._headers) {
        ss << it.first << ": " << it.second << "\r\n";
    }
    ss << "\r\n";
    ss << req._body;
    return ss.str();
}

void Hello(const HttpRequest& req,HttpResponse* rsp)
{
    rsp->SetContent(RequestStr(req),"text/plain");
}

void Login(const HttpRequest& req,HttpResponse* rsp)
{
    rsp->SetContent(RequestStr(req),"text/plain");
}

//保存文件
void PutFile(const HttpRequest &req, HttpResponse *rsp) 
{
    std::string pathname = WWWROOT + req._path;
    Util::WriteFile(pathname, req._body);
}

void DelFile(const HttpRequest &req, HttpResponse *rsp) 
{
    rsp->SetContent(RequestStr(req), "text/plain");
}

int main()
{
    HttpServer server(8080,10);
    server.SetBaseDir(WWWROOT); // 设置静态资源目录
    server.SetThreadCount(3); // 从属线程数量为3
    server.Get("/hello",Hello);
    server.Post("/login",Login);
    server.Put("/niba.txt",PutFile);
    server.Delete("/niba.txt",PutFile);
    server.Listen();

    return 0;
}